package com.caiya.controller;

import com.caiya.cart.Res;
import com.caiya.cart.entity.CartUser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Administrator on 2019/3/22 0022.
 */
@RestController
@Api(description = "车型")
@RequestMapping("/api")
public class MovieController {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class);
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @HystrixCommand(fallbackMethod = "findByIdFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    @GetMapping(value = "/user/{id}")
    @ApiOperation(value = "333",notes = "333")
    public Res user(@PathVariable("id")Long id){
        Res res = null;
        try {
            Res forObject = this.restTemplate.getForObject("http://caiya-cart/api/user/byid/" + id, Res.class);
            res = forObject;
        }catch (Exception e){
            e.printStackTrace();
            res = new Res(Res.CODE_FAIL,e.getMessage());
        }
        return res;
    }

    public Res findByIdFallback(Long id){
//        LOGGER.error("回退方法异常",throwable);
        Res res = new Res();
        res.setCode(0);
        res.setMsg("进入回退方法"+id);
        return res;
    }

    @GetMapping(value = "/log-user-instance")
    public void logUserInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("caiya-cart");
        MovieController.LOGGER.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }
}
